<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <title>AiEditor</title>
  <link rel="stylesheet" href="aieditor-style.css" />
  <script src="marked.min.js"></script>
  <script src="html-docx.min.js"></script>
  <style>
    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    
    html, body {
      height: 100%;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .editor-container {
      width: calc(100% - 40px);
      height: calc(100% - 40px);
      max-width: 1200px;
      background: rgba(255, 255, 255, 0.85);
      backdrop-filter: blur(12px);
      -webkit-backdrop-filter: blur(12px);
      border-radius: 16px;
      box-shadow: 
        0 8px 32px rgba(31, 38, 135, 0.1),
        0 4px 16px rgba(0, 0, 0, 0.05);
      overflow: hidden;
      display: flex;
      flex-direction: column;
      transition: all 0.3s ease;
      border: 1px solid rgba(255, 255, 255, 0.5);
    }
    
    .editor-header {
      background: linear-gradient(90deg, #4a6fa5 0%, #5a8faa 100%);
      color: white;
      padding: 16px 24px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    }
    
    .editor-title {
      font-size: 18px;
      font-weight: 600;
      display: flex;
      align-items: center;
      gap: 8px;
    }
    
    .editor-status {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 14px;
      opacity: 0.9;
    }
    
    .status-indicator {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background: #4ade80;
      animation: pulse 2s infinite;
    }
    
    @keyframes pulse {
      0% { opacity: 1; }
      50% { opacity: 0.5; }
      100% { opacity: 1; }
    }
    
    #aiEditor {
      flex: 1;
      border: none;
      overflow-y: auto;
      background: transparent;
    }
    
    /* 自定义滚动条 */
    #aiEditor::-webkit-scrollbar {
      width: 8px;
    }
    
    #aiEditor::-webkit-scrollbar-track {
      background: rgba(245, 245, 245, 0.3);
      border-radius: 4px;
    }
    
    #aiEditor::-webkit-scrollbar-thumb {
      background: rgba(200, 200, 200, 0.5);
      border-radius: 4px;
      transition: background 0.3s ease;
    }
    
    #aiEditor::-webkit-scrollbar-thumb:hover {
      background: rgba(180, 180, 180, 0.7);
    }
    
    /* 响应式设计 */
    @media (max-width: 768px) {
      .editor-container {
        width: calc(100% - 20px);
        height: calc(100% - 20px);
        border-radius: 12px;
      }
      
      .editor-header {
        padding: 12px 16px;
      }
      
      .editor-title {
        font-size: 16px;
      }
    }
    
    /* 加载动画 */
    .loading {
      display: inline-block;
      width: 16px;
      height: 16px;
      border: 2px solid rgba(255, 255, 255, 0.3);
      border-top: 2px solid white;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
    
    /* 添加微妙的动画效果 */
    .editor-container {
      animation: fadeIn 0.5s ease-out;
    }
    
    .status-btn{
      margin-left: 12px;
      padding: 4px 10px;
      font-size: 13px;
      border: 1px solid rgba(255,255,255,.5);
      background: rgba(255,255,255,.15);
      color: #fff;
      border-radius: 4px;
      cursor: pointer;
      transition: background .2s;
    }
    .status-btn:hover{background: rgba(255,255,255,.25);}

    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(10px); }
      to { opacity: 1; transform: translateY(0); }
    }
  </style>
</head>
<body>
  <div class="editor-container">
    <div class="editor-header">
      <div class="editor-title">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
          <polyline points="14 2 14 8 20 8"></polyline>
          <line x1="16" y1="13" x2="8" y2="13"></line>
          <line x1="16" y1="17" x2="8" y2="17"></line>
          <polyline points="10 9 9 9 8 9"></polyline>
        </svg>
        AiEditor
      </div>
      <div class="editor-status">
        <button id="btnDownloadDocx" class="status-btn" title="保存为 docx 文件">下载</button>
        <button id="btnPull" class="status-btn" title="把最后一条助手消息拉到编辑器">从助手消息编辑</button>
        <button id="btnPush" class="status-btn" title="把编辑器内容发给主页面输入框">发送到输入</button>
        <span class="status-indicator"></span>
        <span>就绪</span>
      </div>
    </div>
    <div id="aiEditor"></div>
  </div>

  <script type="module">
    import { AiEditor } from './aieditor-index.js';

    const origin = window.location.origin;
    let editor = null;

    // 添加加载状态
    const statusElement = document.querySelector('.editor-status span:last-child');
    const statusIndicator = document.querySelector('.status-indicator');

    try {
      statusElement.textContent = '初始化中...';
      statusIndicator.style.background = '#fbbf24';

      editor = new AiEditor({
        element: '#aiEditor',
        placeholder: '点击输入内容，支持 AI 辅助写作...',
        content: '<p><strong>欢迎使用 AiEditor！</strong></p><p>本扩展基于AiEditor开发，这是一个基于 AI 的开源富文本编辑器，支持智能写作辅助、实时协作等功能。</p><p>开始输入您的内容，体验智能化的编辑体验吧！</p>',
        ai: {
          models: {
            openai: {
              customUrl: `${origin}/simple_chat`,
              model: 'super-model',
              apiKey: 'super-secret-key'
            }
          }
        },
        onReady: () => {
          statusElement.textContent = '就绪';
          statusIndicator.style.background = '#4ade80';
        },
        onChange: () => {
          statusElement.textContent = '编辑中...';
          statusIndicator.style.background = '#3b82f6';
          clearTimeout(window.statusTimeout);
          window.statusTimeout = setTimeout(() => {
            statusElement.textContent = '已保存';
            statusIndicator.style.background = '#4ade80';
            setTimeout(() => {
              statusElement.textContent = '就绪';
            }, 1500);
          }, 1000);
        }
      });

    } catch (error) {
      console.error('编辑器初始化失败:', error);
      statusElement.textContent = '初始化失败';
      statusIndicator.style.background = '#ef4444';
    }

    // 添加键盘快捷键提示
    document.addEventListener('keydown', (e) => {
      if (e.ctrlKey || e.metaKey) {
        switch(e.key) {
          case 's':
            e.preventDefault();
            statusElement.textContent = '保存中...';
            statusIndicator.style.background = '#fbbf24';
            setTimeout(() => {
              statusElement.textContent = '已保存';
              statusIndicator.style.background = '#4ade80';
              setTimeout(() => {
                statusElement.textContent = '就绪';
              }, 1000);
            }, 500);
            break;
        }
      }
    });

    /* ===== 复用你已有的 ws 逻辑，只追加功能 ===== */
    const $ = s => document.querySelector(s);
    let ws;

    function initSharedWS() {
      const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
      ws = new WebSocket(`${proto}//${location.host}/ws`);
      ws.onopen = () => ws.send(JSON.stringify({ type: 'get_messages' }));
      ws.onclose = () => setTimeout(initSharedWS, 5000);
      ws.onmessage = (e) => {
        try {
          const d = JSON.parse(e.data);
          if (d.type === 'messages_update' || d.type === 'broadcast_messages') {
            window._messages = d.data.messages;
          }
        } catch {}
      };
    }
    initSharedWS();

    /* 两个按钮事件 */
    $('#btnPull').onclick = () => {
      if (!window._messages) return;
      const bot = [...window._messages].reverse().find(m => m.role === 'assistant');
      if (!bot) {
        editor.setContent('<p>（暂无助手消息）</p>');
        return;
      }
      const txt = bot.pure_content || bot.content || '';
      const html = marked.parse(txt);
      editor.setContent(html);
    };

    $('#btnPush').onclick = () => {
      if (!editor) return;
      const t = editor.getText().trim();
      if (!t) return;
      ws.send(JSON.stringify({ type: 'set_user_input', data: { text: t } }));
    };
    /* ===== 导出 docx ===== */
    document.getElementById('btnDownloadDocx').onclick = () => {
      if (!editor) return;
      // 拿到带格式的 HTML
      const html = editor.getHtml();          // AiEditor 原生 API
      // 拼一个最简完整的 HTML 骨架，让 html-docx-js 更好识别样式
      const fullHtml = `
        <html>
          <head>
            <meta charset="utf-8">
            <title>AiEditor 导出</title>
            <style>
              body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,
                              "Noto Sans",sans-serif;font-size:14px;line-height:1.6;color:#333;}
              h1,h2,h3,h4,h5,h6{margin:12px 0 6px;font-weight:600;}
              p{margin:4px 0;}
              ul,ol{margin:4px 0;padding-left:24px;}
              blockquote{margin:6px 0;padding-left:12px;border-left:4px solid #ccc;color:#555;}
              code{background:#f4f4f4;padding:2px 4px;border-radius:3px;font-size:13px;}
              pre{background:#f6f8fa;padding:8px;border-radius:4px;overflow-x:auto;}
            </style>
          </head>
          <body>${html}</body>
        </html>`;

      // 转二进制
      const converted = htmlDocx.asBlob(fullHtml);

      // 下载
      const fileName = `AiEditor_${new Date().toISOString().slice(0,10)}.docx`;
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        // IE/Edge
        window.navigator.msSaveOrOpenBlob(converted, fileName);
      } else {
        // 现代浏览器
        const link = document.createElement('a');
        link.href = URL.createObjectURL(converted);
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    };
  </script>

</body>
</html>
